package com.ek.service;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.FutureTask;
import java.util.concurrent.LinkedBlockingQueue;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author G.Santoro
 */
public class TaskManager implements Runnable {
    private static final transient Logger log = LoggerFactory.getLogger(TaskManager.class);
    private boolean listening;
    private final BlockingQueue<FutureTask> tasks;
    private final ExecutorService taskHandlerExecutorService;

    public TaskManager() {
        this.tasks = new LinkedBlockingQueue<FutureTask>();
        this.listening = true;
        this.taskHandlerExecutorService = Executors.newCachedThreadPool();
    }

    public void run() {
        log.debug("running ...");
        try {
            while (listening) {
                FutureTask task = tasks.take();
                if (task != null) {
                    log.debug("start of task:{}", task);
                    taskHandlerExecutorService.execute(task);
                }
            }

        } catch (InterruptedException e) {
            log.warn("run InterruptedException" + e);
        
        }

    }

    public boolean put(FutureTask task) {
        try {
            log.debug("put this task in the queue:" + task);
            tasks.put(task);
        
        } catch (InterruptedException e) {
            log.error("put InterruptedException", e);
            return false;
        
        }
        return true;
    }

    public void stop() {
        this.listening = false;
    }

}
